/**
 * 2025/01/01 - 2025/12/31
 */
package com.snail.server.iam.resource.manager;

import com.snail.server.iam.app.entity.App;
import com.snail.server.iam.app.service.AppService;
import com.snail.server.iam.resource.entity.Resource;
import com.snail.server.iam.resource.mapping.ResourceMapping;
import com.snail.server.iam.resource.service.ResourceService;
import com.snail.server.iam.resource.vo.AppResourceVO;
import com.snail.server.iam.resource.vo.ResourceVO;
import com.snail.server.iam.user.entity.UserAppMapping;
import com.snail.server.iam.user.service.UserService;
import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import com.snail.starter.utils.tree.TreeUtil;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author zgadmin
 * @date 2025/9/26 19:17
 */
@Component
public class ResourceManager {

    @javax.annotation.Resource
    ResourceService resourceService;

    @javax.annotation.Resource
    AppService appService;

    @javax.annotation.Resource
    UserService userService;

    @javax.annotation.Resource
    ResourceMapping resourceMapping;

    public AppResourceVO resourceByApp(Long appId) {
        UserContext userContext = UserContextUtils.get();
        App app = appService.checkApp(appId);
        UserAppMapping userApp = userService.checkUserTenant(userContext.getTenantId(), userContext.getUserId(), app.getAppId());
        List<Resource> resources = resourceService.list(userApp.getAppId());
        return AppResourceVO.of(app.getAppId(),
                TreeUtil.buildTree(resources, Resource::getParentId,
                        resource -> resourceMapping.toResourceVO(resource), Resource::getResourceId,
                        ResourceVO::setChildren, ResourceVO::getOrderBy));
    }

}
